package me.linczh.bank.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.linczh.bank.bean.LogBean;
import me.linczh.bank.bean.enums.Department;
import me.linczh.bank.bean.enums.Operation;
import me.linczh.bank.dao.LogDao;
import me.linczh.framework.query.Query;

public class DBLogDao extends BaseDBDaoImpl implements LogDao {

	@Override
	public LogBean create(LogBean _log) {
		// TODO Auto-generated method stub
		_log.setTime(new Date());
		try {
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Statement s = super.conn.createStatement();
			s.execute("insert into log_tbl values (" +
					"'" + _log.getOperation() + "'," +
					"'" + _log.getEmployee() + "'," +
					"'" + _log.getEmployeename() + "'," +
					"'" + _log.getDepartment() + "'," +
					"'" + _log.getAccount() + "'," +
					"'" + _log.getUsername() + "'," +
					"'" + _log.getIdentity() + "'," +
					+ _log.getChange() + "," +
					+ _log.getBalance() + "," +
					"'" + fmt.format(_log.getTime()) + "')");
			return _log;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public List<LogBean> query(Query<LogBean> query) {
		// TODO Auto-generated method stub
		try {
			Statement s = super.conn.createStatement();
			ResultSet result = s.executeQuery("select * from log_tbl");
			SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			List<LogBean> logs = new ArrayList<LogBean>();
			while (result.next()) {
				LogBean bean = new LogBean();
				bean.setOperation(Operation.valueOf(result.getString(1)));
				bean.setEmployee(result.getString(2));
				bean.setEmployeename(result.getString(3));
				bean.setDepartment(Department.valueOf(result.getString(4)));
				bean.setAccount(result.getString(5));
				bean.setUsername(result.getString(6));
				bean.setIdentity(result.getString(7));
				bean.setChange(result.getDouble(8));
				bean.setBalance(result.getDouble(9));
				bean.setTime(fmt.parse(result.getString(10)));
				if (query.matched(bean)) logs.add(bean);
			}
			return logs;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ArrayList<LogBean>();
	}

}
